package handler;

import com.lmax.disruptor.EventHandler;
import event.EventObject;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Logger;

/**
 * Created by dongjigong on 2018/5/28.
 *
 * @Email osbornjonny@126.com
 * @Description
 */
public class BaseEventHandler implements EventHandler<EventObject> {


    private static final Map<String, Method> cachedClassObject = new TreeMap<>();

    private static final Logger logger = Logger.getLogger("");

    @Override
    public void onEvent(EventObject event, long sequence, boolean endOfBatch) throws Exception {

        String consumerName = event.getProducerName();
        Method method = cachedClassObject.get(consumerName);
        if (method == null) {
            logger.info("can not find producer" + consumerName);
            return;
        }
        Class<?> returnType = method.getReturnType();
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (!event.getEventParameters().getClass().equals(parameterTypes)) {
            logger.info("parameters type illegal!");
        }
        if (Void.class == returnType) {
            method.invoke(event.getEventParameters());
            return;
        }
        Object result = method.invoke(event.getEventParameters());
        event.setEventResult(result);
    }
}